//小程序根目录：npm init
//小程序根目录：npm install crypto-js --save
//在微信开发者工具中"构建npm"
//js中引入import CryptoJS from 'crypto-js'
import CryptoJS from 'crypto-js'　

Page({
  data: {
    ApiUrl:"https://iot-app-prod.fengdada.cn/mk/api",
    PrinterId:"xxxxxxxx",
    AppId:"xxxxxxxx",
    AppSecret:"xxxxxxxx",
    ShareCode:"xxxxxxxx", 
    VerificationCode:"", 
    TemplateId : "xxxxxxxx",
    PData:"",
    Result:"",
},
bindVerificationCode (e) {
    this.setData({
      VerificationCode: e.detail.value
    })
},
bindShareCode (e) {
    this.setData({
      ShareCode: e.detail.value
    })
},
//公共方法
hexstr2ab(hexstr) {
  var hex = hexstr.toString();
  var bytes = new Uint8Array(hex.length / 2);
  for (var i = 0; i < bytes.length; i++) {
    bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
  }
  return bytes.buffer;
},
encode(jsonData, nonce) {
  const jsonBytes = new TextEncoder().encode(jsonData);
  const bizData = new TextDecoder().decode(jsonBytes);
  const sign_ori = `${bizData}${nonce}${this.data.AppSecret}`;
  let hash = CryptoJS.MD5(sign_ori);
  let wordArray = hash.words;
  CryptoJS.lib.WordArray.create(wordArray).clamp();
  let sign = CryptoJS.enc.Base64.stringify(hash);
  return sign;
},
generateVerificationCode() {
    let verificationCode = '';
    for (let i = 0; i < 6; i++) {
      verificationCode += Math.floor(Math.random() * 10);
    }
    return verificationCode;
  },
DoMyPost(URL, json_BizData){
    const ts = Math.round(new Date().getTime());
    const nonce= this.generateVerificationCode();
    const sign= this.encode(json_BizData,nonce)
    const data = {
      "bizData": json_BizData,
      "nonce": nonce,
      "appId": this.data.AppId,
      "timestamp": String(ts)
    };
    console.log(sign);
    const headers = { "Content-Type": "application/json", "sign": sign };
    let that=this;
    wx.request({
      url: URL,
      method: 'POST',
      header: headers,
      data: data,
      success: function (res) {
        console.log(res.data)
        that.setData({
          Result:("{code:"+res.data.code+","+"desc:"+res.data.desc+","+","+"id:"+res.data.id+","+"desc:"+res.data.desc+","+"data:"+res.data.data+"}"),
        });
      },
      fail: function (res) {
        console.log('request failed')
      },
      complete: function (res) {
        console.log('request completed')
      }
    })
   

  },
//1、获取验证码
PrintCaptcha(){
    const URL = this.data.ApiUrl+"/print/captcha";
    let BizData = {'printerId': this.data.PrinterId};
    let json_BizData = JSON.stringify(BizData);
    this.DoMyPost(URL, json_BizData);
  },
  //2、绑定打印机
PrintBind(){
    const URL = this.data.ApiUrl+"/printer/bind"
    let BizData = {'printerId': this.data.PrinterId,'captcha':this.data.VerificationCode}
    let json_BizData = JSON.stringify(BizData);
    this.DoMyPost(URL, json_BizData)
  },
//3、云打印
Print(){
    const waybillPrinterData = {
      "receiveManAddress":"塘苗路18号",
      "orderId":"10256485649",
      "needFetch":"true",
      "packageWeight":"",
      "companyName":"",
      "sendProvince":"浙江省",
      "errorCode":"",
      "receiverProvince":"浙江省",
      "receiverCity":"杭州市",
      "senderMan":"张三",
      "senderArea":"西湖区",
      "receiveMan":"李四",
      "postStationId":"",
      "itemName":"",
      "specialType":"代收货款",
      "senderPostcode":"",
      "payMethod":"0",
      "id":"1933",
      "logisticCode":"BestSmart10256485649",
      "machineCode":"1843923524226238",
      "errorDesc":"",
      "balanceStatus":"",
      "specialMoney":" 39 元",
      "expressType":"0",
      "sendCounty":"西湖区",
      "weight":"",
      "receiverPostcode":"",
      "version":"1",
      "senderCity":"杭州市",
      "receiveProvince":"浙江省",
      "printResult":"NONE",
      "sendMan":"张三",
      "companyId":"",
      "expressCost":"",
      "receiverManPhone":"18598765432",
      "mainId":"",
      "senderManPhone":"15012345678",
      "remark1":"",
      "remark3":"",
      "receiveCounty":"西湖区",
      "remark2":"",
      "lastUpdateTime":"Wed Jul 29 13:53:06 CST 2015",
      "markDestination":"测-测试单(2)(浙-2)",
      "sendCity":"杭州市",
      "pkgCode":"测试测试包",
      "receiverMan":"李四",
      "errorInfo":"null",
      "remark":"【批次1/1】备注",
      "sendManPhone":"15012345678",
      "batchId":"1/1",
      "pickBy":"",
      "result":"SUCCESS",
      "mailNo":"12345678901234",
      "shippingStatus":"NOMESSAGE",
      "serialVersionUID":"-1229572053273904313",
      "richItemInformation":"",
      "receiveManPhone":"18598765432",
      "udf7":"",
      "billProvideSiteCode":"200000",
      "logisticsProviderCode":"HTKY",
      "udf8":"",
      "printCount":"1",
      "senderManAddress":"教工路1号",
      "custId":"null",
      "itemWeight":"",
      "receiverManAddress":"塘苗路18号",
      "isReprint":"false",
      "orderSource":"BestSmart",
      "udf5":"测试",
      "udf6":"",
      "senderProvince":"浙江省",
      "receiverArea":"西湖区",
      "udf3":"",
      "udf4":"",
      "udf1":"",
      "userId":"",
      "udf2":"",
      "postStationName":"",
      "itemCount":"0",
      "logisticProviderID":"HTKY",
      "billProvideSiteName":"上海分拨中心",
      "createTime":"Wed Jul 29 13:37:40 CST 2015",
      "receiveCity":"杭州市",
      "sendManAddress":"教工路1号",
      "printTime":"",
      "username":""
      };
    const printDataList = [{"waybillPrinterData": waybillPrinterData, "templateId": this.data.TemplateId}];
    const URL = this.data.ApiUrl+"/print"
    let BizData = {'printerId': this.data.PrinterId,'shareCode':this.data.ShareCode,'printData':printDataList}
    let json_BizData = JSON.stringify(BizData);
    this.DoMyPost(URL, json_BizData)
  },
//4、云打印机状态查询
QueryPrintStatus(){
    const URL = this.data.ApiUrl+"/printer/status/query"
    console.log(this.data.VerificationCode);
    let BizData = {'printerId': this.data.PrinterId,'shareCode':this.data.ShareCode}
    let json_BizData = JSON.stringify(BizData);
    this.DoMyPost(URL, json_BizData)
  }
})
